"""
Command-line interface for Qwen3 client
"""

import argparse
import sys
import json
from pathlib import Path
from typing import Optional

from .core import Qwen3Client, Qwen3Config
from .paper_analyzer import PaperStructureAnalyzer
from .utils import setup_logging, load_env_file, validate_api_key
from .history import QAHistoryManager
import re
from concurrent.futures import ThreadPoolExecutor
import time


def compact_claude_dialogue_chunk(lines: list, start_idx: int = 0) -> str:
    """
    Compact a chunk of Claude CLI dialogue lines.
    """
    if not lines:
        return ""
    
    compacted_lines = []
    
    # Process the dialogue chunk
    in_command_output = False
    in_tool_output = False
    in_todo_section = False
    in_summary_section = False
    
    for i, line in enumerate(lines):
        try:
            stripped = line.strip()
            
            # Skip empty lines in certain contexts unless we're in special sections
            if not stripped and not (in_todo_section or in_summary_section):
                continue
                
            # User commands (lines starting with >)
            if stripped.startswith('>'):
                if in_command_output or in_tool_output:
                    compacted_lines.append("")  # Add spacing
                compacted_lines.append(stripped)  # Keep original > format
                in_command_output = True
                in_tool_output = False
                in_todo_section = False
                in_summary_section = False
                
            # Assistant responses (lines starting with ●)
            elif stripped.startswith('●'):
                if in_command_output:
                    compacted_lines.append("")  # Add spacing
                    
                # Check for special sections that need context retention
                if "Update Todos" in stripped:
                    compacted_lines.append(stripped)
                    in_todo_section = True
                    in_summary_section = False
                elif "Summary" in stripped:
                    compacted_lines.append(stripped)
                    in_summary_section = True
                    in_todo_section = False
                else:
                    compacted_lines.append(stripped)  # Keep original ● format
                    in_todo_section = False
                    in_summary_section = False
                    
                in_command_output = False
                in_tool_output = False
                
            # Tool usage patterns (Read, Bash, Edit, etc.)
            elif any(tool in stripped for tool in ['Read(', 'Bash(', 'Edit(', 'Write(', 'Update(', 'Search(']):
                if not in_tool_output and not (in_todo_section or in_summary_section):
                    compacted_lines.append("")
                    compacted_lines.append("**Tools used:**")
                    in_tool_output = True
                
                # In todo/summary sections, keep the tool calls as-is
                if in_todo_section or in_summary_section:
                    compacted_lines.append(stripped)
                else:
                    # Extract tool name and key info for regular sections
                    tool_match = re.search(r'(\w+)\((.*?)\)', stripped)
                    if tool_match:
                        tool_name, tool_args = tool_match.groups()
                        compacted_lines.append(f"- {tool_name}: {tool_args[:100]}{'...' if len(tool_args) > 100 else ''}")
                
            # Tool output indicators (⎿)
            elif stripped.startswith('⎿'):
                # In todo/summary sections, keep tool output context
                if in_todo_section or in_summary_section:
                    compacted_lines.append(stripped)
                else:
                    # Skip most tool output details in regular sections
                    continue
                
            # Todo list items and summary content
            elif in_todo_section and (stripped.startswith('☒') or stripped.startswith('☐') or 
                                     stripped.startswith('-') or stripped.startswith('•') or
                                     'List(' in stripped or any(c in stripped for c in ['✅', '⎿'])):
                compacted_lines.append(stripped)
                
            # Summary section content - keep result lines and key information
            elif in_summary_section and (stripped.startswith('Result:') or 
                                        stripped.startswith('-') or stripped.startswith('•') or
                                        stripped.startswith('🎯') or stripped.startswith('🏗️') or
                                        stripped.startswith('🚀') or stripped.startswith('📊') or
                                        any(indicator in stripped for indicator in ['✅', 'Complete', 'Achievement', 'Success', 'Ready'])):
                compacted_lines.append(stripped)
                
            # Error messages and important output
            elif any(keyword in stripped.lower() for keyword in ['error:', 'traceback', 'failed', 'success']):
                if not in_tool_output:
                    compacted_lines.append(f"Result: {stripped}")
                
            # Skip verbose command output unless it's very short
            elif in_command_output and len(stripped) > 100:
                continue
                
            # Keep short important lines
            elif in_command_output and len(stripped) > 0 and len(stripped) <= 100:
                if not any(skip in stripped.lower() for skip in ['deprecation:', 'requirement already satisfied', 'looking in indexes']):
                    compacted_lines.append(f"  {stripped}")
        
        except Exception as e:
            # Skip problematic lines but continue processing
            print(f"Warning: Error processing line {i}: {e}")
            continue
    
    return '\n'.join(compacted_lines)


def compact_claude_dialogue(content: str) -> str:
    """
    Compact Claude CLI dialogue by removing verbose output and keeping key interactions.
    For large files (>300 lines), splits into chunks for faster processing.
    """
    lines = content.split('\n')
    total_lines = len(lines)
    
    # Skip the initial welcome box and add header
    result_lines = ["# Claude CLI Session Summary\n"]
    i = 0
    while i < len(lines) and not lines[i].strip().startswith('>'):
        if lines[i].startswith('╰') and '─' in lines[i]:
            break
        i += 1
    
    # Get the dialogue content (skip welcome box)
    dialogue_lines = lines[i:]
    
    if len(dialogue_lines) <= 300:
        # Process small files normally
        compacted = compact_claude_dialogue_chunk(dialogue_lines)
        result_lines.append(compacted)
    else:
        # Process large files in chunks with smart splitting at empty lines
        max_chunk_size = 300
        chunk_data = []
        current_chunk = []
        current_start = 0
        
        for i, line in enumerate(dialogue_lines):
            current_chunk.append(line)
            
            # Check if we should split at this point
            should_split = (
                len(current_chunk) >= max_chunk_size and  # Reached max size
                line.strip() == "" and                     # Current line is empty
                i < len(dialogue_lines) - 1               # Not the last line
            )
            
            if should_split:
                # Split here - add current chunk and start new one
                chunk_data.append((current_chunk.copy(), current_start))
                current_start = i + 1
                current_chunk = []
        
        # Add the final chunk if it has content
        if current_chunk:
            chunk_data.append((current_chunk, current_start))
        
        # Process chunks in parallel (limited to 4 threads to avoid overwhelming)
        num_chunks = len(chunk_data)
        chunks = []
        with ThreadPoolExecutor(max_workers=min(4, num_chunks)) as executor:
            # Submit all chunks for processing
            future_to_chunk = {
                executor.submit(compact_claude_dialogue_chunk, chunk_lines, start_idx): (chunk_lines, start_idx)
                for chunk_lines, start_idx in chunk_data
            }
            
            # Collect results in order
            chunk_results = {}
            for future in future_to_chunk:
                chunk_lines, start_idx = future_to_chunk[future]
                try:
                    compacted_chunk = future.result(timeout=30)  # 30 second timeout per chunk
                    if compacted_chunk.strip():
                        chunk_results[start_idx] = compacted_chunk
                except Exception as e:
                    # Skip failed chunks but continue processing
                    print(f"Warning: Failed to process chunk starting at line {start_idx}: {e}")
        
        # Combine chunks in order
        for start_idx in sorted(chunk_results.keys()):
            chunks.append(chunk_results[start_idx])
        
        if chunks:
            result_lines.extend(chunks)
    
    # Clean up multiple empty lines
    final_result = []
    prev_empty = False
    combined_content = '\n'.join(result_lines)
    
    for line in combined_content.split('\n'):
        is_empty = line.strip() == ""
        if not (is_empty and prev_empty):
            final_result.append(line)
        prev_empty = is_empty
    
    return '\n'.join(final_result)


def compress_claude_dialogue(content: str) -> str:
    """
    Compress Claude CLI dialogue by filtering out edit contexts with line numbers.
    Removes lines that match the format: '    num    content' or similar edit diff formats.
    """
    lines = content.split('\n')
    filtered_lines = []
    in_edit_context = False
    
    for line in lines:
        # Check if line matches edit context format (7+ spaces + line number + 1 space + content)
        # Pattern: '       47 +  ## Troubleshooting', '        14 -  try:', '       46    '
        if re.match(r'^\s{7,}\d+\s', line):
            # Skip lines that look like edit context (line numbers with content)
            in_edit_context = True
            continue
            
        # Check for continuation lines with extra indentation (like wrapped lines)
        elif in_edit_context and re.match(r'^\s{10,}[+-]', line):
            # Skip wrapped diff lines like '          - SourceLocation, File' or '           + following:'
            continue
            
        # Check for lines that start with tab and are part of edit results
        elif line.startswith('\t') or re.match(r'^\s{8,20}\d+→', line):
            # Skip lines that are typical edit output with line numbers like '     11→'
            continue
        
        # Reset edit context flag when we see a non-edit line
        else:
            in_edit_context = False
            
        # Also skip lines that are typical diff markers within edit contexts
        stripped = line.strip()
        if (stripped.startswith('-') or stripped.startswith('+')) and len(line) > 10:
            # Check if this looks like a diff line within an edit context
            # (not a regular bullet point or list item)
            if not any(marker in stripped[:5] for marker in ['- ', '+ ', '* ', '• ']):
                continue
        
        # Keep the line
        filtered_lines.append(line)
    
    # Clean up multiple consecutive empty lines
    final_lines = []
    prev_empty = False
    
    for line in filtered_lines:
        is_empty = line.strip() == ""
        if not (is_empty and prev_empty):
            final_lines.append(line)
        prev_empty = is_empty
    
    return '\n'.join(final_lines)


def create_simple_parser():
    """Create parser for simple interface (like qwen-translate)"""
    parser = argparse.ArgumentParser(
        description="Qwen3 Client - AI-powered text analysis and question answering"
    )
    
    # Simple interface arguments
    parser.add_argument("prompt", nargs="?", help="Text prompt to ask Qwen3")
    parser.add_argument("--file", "-f", type=str, help="File containing text to use as prompt")
    parser.add_argument("--compact", action="store_true", help="Compact dialogue file (use with --file to compress Claude CLI exports)")
    parser.add_argument("--compress", action="store_true", help="Compress dialogue file by filtering out edit contexts (use with --file)")
    
    # History commands
    parser.add_argument("--list", action="store_true", help="List all Q&A history with question IDs")
    parser.add_argument("--show", type=int, metavar="QUESTION_ID", help="Show full Q&A for specific question ID")
    
    # Global options
    parser.add_argument("--config", type=str, help="Path to config file")
    parser.add_argument("--api-key", type=str, help="Dashscope API key")
    parser.add_argument("--base-url", type=str, help="API base URL")
    parser.add_argument("--model", type=str, help="Model name")
    parser.add_argument("--log-level", type=str, default="INFO", 
                       choices=["DEBUG", "INFO", "WARNING", "ERROR"],
                       help="Logging level")
    parser.add_argument("--log-file", type=str, help="Log file path")
    parser.add_argument("--env-file", type=str, help="Environment file path")
    parser.add_argument("--system-prompt", type=str, help="System prompt for simple mode")
    parser.add_argument("--plus", action="store_true", help="Use qwen3-235b-a22b-instruct-2507 model for higher quality")
    
    return parser


def create_subcommand_parser():
    """Create parser for advanced subcommand interface"""
    parser = argparse.ArgumentParser(
        description="Qwen3 Client - AI-powered text analysis and question answering"
    )
    
    # Global options
    parser.add_argument("--config", type=str, help="Path to config file")
    parser.add_argument("--api-key", type=str, help="Dashscope API key")
    parser.add_argument("--base-url", type=str, help="API base URL")
    parser.add_argument("--model", type=str, help="Model name")
    parser.add_argument("--log-level", type=str, default="INFO", 
                       choices=["DEBUG", "INFO", "WARNING", "ERROR"],
                       help="Logging level")
    parser.add_argument("--log-file", type=str, help="Log file path")
    parser.add_argument("--env-file", type=str, help="Environment file path")
    parser.add_argument("--plus", action="store_true", help="Use qwen3-235b-a22b-instruct-2507 model for higher quality")
    
    # Subcommands
    subparsers = parser.add_subparsers(dest="command", help="Available commands", required=True)
    
    # Ask command
    ask_parser = subparsers.add_parser("ask", help="Ask Qwen3 a question")
    ask_parser.add_argument("question", type=str, help="Question to ask")
    ask_parser.add_argument("--system-prompt", type=str, help="System prompt")
    ask_parser.add_argument("--chinese", action="store_true", 
                           help="Use Chinese technical response mode")
    ask_parser.add_argument("--domain", type=str, default="技术", 
                           help="Technical domain for Chinese mode")
    ask_parser.add_argument("--context-file", type=str, 
                           help="JSON file containing context information")
    ask_parser.add_argument("--output", type=str, help="Output file path")
    
    # Batch ask command
    batch_parser = subparsers.add_parser("batch", help="Ask multiple questions")
    batch_parser.add_argument("questions_file", type=str, 
                             help="File containing questions (one per line or JSON)")
    batch_parser.add_argument("--output-dir", type=str, 
                             help="Output directory for answers")
    batch_parser.add_argument("--system-prompt", type=str, help="System prompt")
    batch_parser.add_argument("--chinese", action="store_true", 
                             help="Use Chinese technical response mode")
    
    # Test connection command
    test_parser = subparsers.add_parser("test", help="Test API connection")
    
    return parser


def main():
    """Main CLI entry point"""
    # Check if first argument is a known subcommand to decide parsing strategy
    known_commands = ['ask', 'batch', 'test']
    use_subcommands = len(sys.argv) > 1 and sys.argv[1] in known_commands
    
    if use_subcommands:
        # Use the old subcommand-based parser
        parser = create_subcommand_parser()
        args = parser.parse_args()
    else:
        # Use simple interface parser (like qwen-translate)  
        parser = create_simple_parser()
        args = parser.parse_args()
    
    # Setup logging
    logger = setup_logging(args.log_level, args.log_file)
    
    # Load environment file if specified
    if args.env_file:
        load_env_file(args.env_file)
    else:
        load_env_file()  # Try to load from default locations
    
    try:
        # Create config
        config = create_config_from_args(args)
        
        # Create client
        client = Qwen3Client(config, logger)
        
        # Execute command
        if hasattr(args, 'command') and args.command:
            # Subcommand mode
            if args.command == "ask":
                handle_ask_command(client, args, logger)
            elif args.command == "batch":
                handle_batch_command(client, args, logger)
            elif args.command == "test":
                handle_test_command(client, logger)
        elif hasattr(args, 'list') and args.list:
            # History list command
            handle_history_list_command(logger)
        elif hasattr(args, 'show') and args.show:
            # History show command
            handle_history_show_command(args.show, logger)
        elif hasattr(args, 'prompt') and (args.prompt or args.file):
            # Simple interface mode (like qwen-translate)
            handle_simple_command(client, args, logger)
        else:
            # Show help based on which parser we used
            known_commands = ['ask', 'batch', 'test']
            if len(sys.argv) > 1 and sys.argv[1] in known_commands:
                create_subcommand_parser().print_help()
            else:
                create_simple_parser().print_help()
            sys.exit(1)
            
    except Exception as e:
        logger.error(f"Error: {e}")
        sys.exit(1)


def analyze_paper_main():
    """Main entry point for paper analysis CLI"""
    parser = argparse.ArgumentParser(
        description="Analyze paper structure using Qwen3"
    )
    
    parser.add_argument("paper_file", type=str, help="Path to paper file")
    parser.add_argument("--api-key", type=str, help="Dashscope API key")
    parser.add_argument("--base-url", type=str, help="API base URL")
    parser.add_argument("--model", type=str, help="Model name")
    parser.add_argument("--output", type=str, help="Output JSON file path")
    parser.add_argument("--extract-sections", type=str, nargs="+",
                       help="Section types to extract content for")
    parser.add_argument("--output-dir", type=str, 
                       help="Directory to save extracted section content")
    parser.add_argument("--log-level", type=str, default="INFO",
                       choices=["DEBUG", "INFO", "WARNING", "ERROR"])
    
    args = parser.parse_args()
    
    # Setup logging
    logger = setup_logging(args.log_level)
    
    try:
        # Load environment
        load_env_file()
        
        # Create config
        config = create_config_from_args(args)
        
        # Create client and analyzer
        client = Qwen3Client(config, logger)
        analyzer = PaperStructureAnalyzer(client, logger)
        
        # Analyze paper
        paper_path = Path(args.paper_file)
        if not paper_path.exists():
            logger.error(f"Paper file not found: {paper_path}")
            sys.exit(1)
        
        logger.info(f"Analyzing paper: {paper_path}")
        analysis = analyzer.analyze_paper_file(paper_path)
        
        # Save analysis results
        if args.output:
            output_path = Path(args.output)
            with open(output_path, 'w', encoding='utf-8') as f:
                json.dump(analysis, f, indent=2, ensure_ascii=False)
            logger.info(f"Analysis saved to: {output_path}")
        else:
            print(json.dumps(analysis, indent=2, ensure_ascii=False))
        
        # Extract specific sections if requested
        if args.extract_sections:
            section_content = analyzer.extract_section_content(
                paper_path, args.extract_sections
            )
            
            if args.output_dir:
                output_dir = Path(args.output_dir)
                output_dir.mkdir(parents=True, exist_ok=True)
                
                for section_type, content in section_content.items():
                    if content:
                        section_file = output_dir / f"{section_type}.md"
                        with open(section_file, 'w', encoding='utf-8') as f:
                            f.write(content)
                        logger.info(f"Section '{section_type}' saved to: {section_file}")
            else:
                for section_type, content in section_content.items():
                    print(f"\n=== {section_type.upper()} ===\n")
                    print(content)
                    print("\n" + "="*50 + "\n")
        
        logger.info("Paper analysis completed successfully")
        
    except Exception as e:
        logger.error(f"Error: {e}")
        sys.exit(1)


def create_config_from_args(args) -> Qwen3Config:
    """Create Qwen3Config from command line arguments"""
    # Start with auto-config which handles .env loading
    try:
        config = Qwen3Config.auto_config()
    except ValueError as e:
        # If auto-config fails and no CLI args provided, raise error
        if not (hasattr(args, 'api_key') and args.api_key):
            raise ValueError(f"Configuration failed: {e}. Please set DASHSCOPE_API_KEY or use --api-key")
        # Create minimal config if CLI args provided
        config = Qwen3Config(api_key="", skip_validation=True)
    
    # Override with command line arguments
    if hasattr(args, 'api_key') and args.api_key:
        config.api_key = args.api_key
        config.skip_validation = False  # If API key provided via CLI, enable validation
    if hasattr(args, 'base_url') and args.base_url:
        config.base_url = args.base_url
    if hasattr(args, 'model') and args.model:
        config.model_name = args.model
    
    # Handle --plus parameter to use higher quality model
    if hasattr(args, 'plus') and args.plus:
        config.model_name = "qwen3-235b-a22b-instruct-2507"
    
    # Only validate API key if validation is not skipped
    if not config.skip_validation and not validate_api_key(config.api_key):
        raise ValueError("Valid API key is required. Set DASHSCOPE_API_KEY, use --api-key, or set QWEN_SKIP_API_VALIDATION=true")
    
    return config


def handle_ask_command(client: Qwen3Client, args, logger):
    """Handle ask command"""
    # Load context if provided
    context = {}
    if args.context_file:
        context_path = Path(args.context_file)
        if context_path.exists():
            with open(context_path, 'r', encoding='utf-8') as f:
                context = json.load(f)
            logger.info(f"Loaded context from: {context_path}")
    
    # Ask question
    if args.chinese:
        response = client.ask_chinese_technical(
            args.question, context, args.domain
        )
    elif context:
        response = client.ask_with_context(
            args.question, context, args.system_prompt
        )
    else:
        response = client.ask(args.question, args.system_prompt)
    
    # Output response
    if args.output:
        output_path = Path(args.output)
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(response)
        logger.info(f"Response saved to: {output_path}")
    else:
        print(response)


def handle_batch_command(client: Qwen3Client, args, logger):
    """Handle batch command"""
    # Load questions
    questions_path = Path(args.questions_file)
    if not questions_path.exists():
        raise FileNotFoundError(f"Questions file not found: {questions_path}")
    
    questions = []
    with open(questions_path, 'r', encoding='utf-8') as f:
        content = f.read().strip()
        
        # Try to parse as JSON first
        try:
            data = json.loads(content)
            if isinstance(data, list):
                questions = data
            elif isinstance(data, dict) and 'questions' in data:
                questions = data['questions']
            else:
                raise ValueError("Invalid JSON format")
        except json.JSONDecodeError:
            # Parse as line-separated questions
            questions = [line.strip() for line in content.split('\n') if line.strip()]
    
    logger.info(f"Loaded {len(questions)} questions")
    
    # Process questions
    results = client.batch_ask(questions, args.system_prompt)
    
    # Save results
    if args.output_dir:
        output_dir = Path(args.output_dir)
        output_dir.mkdir(parents=True, exist_ok=True)
        
        for i, (question, answer) in enumerate(results.items(), 1):
            filename = f"answer_{i:03d}.md"
            answer_file = output_dir / filename
            
            with open(answer_file, 'w', encoding='utf-8') as f:
                f.write(f"# Question {i}\n\n")
                f.write(f"**Question**: {question}\n\n")
                f.write(f"**Answer**:\n\n{answer}\n")
            
            logger.info(f"Answer {i} saved to: {answer_file}")
        
        # Also save summary
        summary_file = output_dir / "summary.json"
        with open(summary_file, 'w', encoding='utf-8') as f:
            json.dump(results, f, indent=2, ensure_ascii=False)
        logger.info(f"Summary saved to: {summary_file}")
    else:
        # Print results
        for i, (question, answer) in enumerate(results.items(), 1):
            print(f"\n=== QUESTION {i} ===")
            print(question)
            print(f"\n=== ANSWER {i} ===")
            print(answer)
            print("\n" + "="*50)


def handle_test_command(client: Qwen3Client, logger):
    """Handle test command"""
    logger.info("Testing connection to Qwen3 API...")
    
    try:
        if client.validate_connection():
            logger.info("✅ Connection test successful")
            print("Connection to Qwen3 API is working correctly")
        else:
            logger.error("❌ Connection test failed")
            print("Failed to connect to Qwen3 API")
            sys.exit(1)
    except Exception as e:
        logger.error(f"❌ Connection test error: {e}")
        print(f"Connection test failed with error: {e}")
        sys.exit(1)


def handle_simple_command(client: Qwen3Client, args, logger):
    """Handle simple interface commands (like qwen-translate)"""
    if args.file and (args.compact or args.compress):
        # Handle compact or compress mode for dialogue files
        file_path = Path(args.file)
        if not file_path.exists():
            logger.error(f"File not found: {file_path}")
            sys.exit(1)
        
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # Check file size for progress reporting
        line_count = len(content.split('\n'))
        
        if args.compact:
            logger.info(f"Compacting dialogue from: {file_path} ({line_count} lines)")
            
            if line_count > 300:
                logger.info(f"Large file detected, processing in chunks for better performance...")
            
            # Compact the dialogue
            start_time = time.time()
            processed_content = compact_claude_dialogue(content)
            duration = time.time() - start_time
            
            logger.info(f"Compaction completed in {duration:.2f} seconds")
            
            # Create output filename like input_filename_compact.md
            stem = file_path.stem
            output_file = file_path.parent / f"{stem}_compact.txt"
            
        elif args.compress:
            logger.info(f"Compressing dialogue from: {file_path} ({line_count} lines)")
            
            # Compress the dialogue (filter out edit contexts)
            start_time = time.time()
            processed_content = compress_claude_dialogue(content)
            duration = time.time() - start_time
            
            logger.info(f"Compression completed in {duration:.2f} seconds")
            
            # Create output filename like input_filename_compress.md
            stem = file_path.stem
            output_file = file_path.parent / f"{stem}_compress.md"
        
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(processed_content)
        
        # Count lines in output file
        output_line_count = len(processed_content.split('\n'))
        
        action = "Compacted" if args.compact else "Compressed"
        logger.info(f"{action} dialogue saved to: {output_file} ({output_line_count} lines)")
        return
    
    # Regular prompt/response handling
    prompt = ""
    output_file = None
    
    if args.file:
        # Read prompt from file
        file_path = Path(args.file)
        if not file_path.exists():
            logger.error(f"File not found: {file_path}")
            sys.exit(1)
        
        with open(file_path, 'r', encoding='utf-8') as f:
            prompt = f.read().strip()
        
        logger.info(f"Loaded prompt from: {file_path}")
        
        # Determine output file for markdown files
        if file_path.suffix.lower() in ['.md', '.markdown']:
            # Create output filename like input_answer.md
            stem = file_path.stem
            output_file = file_path.parent / f"{stem}_answer{file_path.suffix}"
    
    elif args.prompt:
        # Use direct prompt
        prompt = args.prompt
    
    else:
        logger.error("Either prompt text or --file must be provided")
        sys.exit(1)
    
    if not prompt:
        logger.error("No prompt text found")
        sys.exit(1)
    
    # Ask the question
    logger.info("Sending prompt to Qwen3...")
    try:
        response = client.ask(prompt, args.system_prompt)
        
        if output_file:
            # Save to output file
            with open(output_file, 'w', encoding='utf-8') as f:
                f.write(response)
            logger.info(f"Response saved to: {output_file}")
        else:
            # Print to screen
            print(response)
            
    except Exception as e:
        logger.error(f"Error getting response: {e}")
        sys.exit(1)


def handle_history_list_command(logger):
    """Handle --list command to show Q&A history"""
    try:
        history_manager = QAHistoryManager()
        entries = history_manager.get_entries(limit=50)  # Show last 50 entries
        
        if not entries:
            print("No Q&A history found.")
            return
        
        print(f"Found {len(entries)} Q&A entries:\n")
        print(f"{'ID':<5} {'Model':<10} {'Date':<20} {'Question':<60}")
        print("-" * 95)
        
        for entry in entries:
            date_str = entry.timestamp.strftime("%Y-%m-%d %H:%M:%S") if entry.timestamp else "Unknown"
            chinese_indicator = " (中文)" if entry.chinese_mode else ""
            domain_info = f" [{entry.domain}]" if entry.domain else ""
            
            print(f"{entry.id:<5} {entry.model:<10} {date_str:<20} {entry.question_preview:<60}")
            if chinese_indicator or domain_info:
                print(f"{'':26}{chinese_indicator}{domain_info}")
        
        # Show statistics
        stats = history_manager.get_statistics()
        print(f"\n📊 Statistics:")
        print(f"   Total entries: {stats['total_entries']}")
        print(f"   Qwen entries: {stats['qwen_entries']}")
        print(f"   DeepSeek entries: {stats['deepseek_entries']}")
        print(f"   OSS entries: {stats['oss_entries']}")
        print(f"   Chinese entries: {stats['chinese_entries']}")
        print(f"   Recent (7 days): {stats['recent_entries']}")
        if stats['avg_response_time']:
            print(f"   Avg response time: {stats['avg_response_time']:.2f}s")
        
    except Exception as e:
        logger.error(f"Error listing history: {e}")
        sys.exit(1)


def handle_history_show_command(question_id: int, logger):
    """Handle --show command to display specific Q&A entry"""
    try:
        history_manager = QAHistoryManager()
        entry = history_manager.get_entry(question_id)
        
        if not entry:
            print(f"No Q&A entry found with ID {question_id}")
            sys.exit(1)
        
        # Display the entry
        print(f"📋 Q&A Entry #{entry.id}")
        print("=" * 80)
        
        # Metadata
        date_str = entry.timestamp.strftime("%Y-%m-%d %H:%M:%S") if entry.timestamp else "Unknown"
        print(f"🕒 Date: {date_str}")
        print(f"🤖 Model: {entry.model}")
        if entry.chinese_mode:
            print(f"🇨🇳 Chinese Mode: Yes (Domain: {entry.domain or 'N/A'})")
        if entry.system_prompt:
            print(f"⚙️  System Prompt: {entry.system_prompt[:100]}{'...' if len(entry.system_prompt) > 100 else ''}")
        if entry.response_time:
            print(f"⏱️  Response Time: {entry.response_time:.2f}s")
        if entry.tokens_used:
            print(f"🔢 Tokens Used: {entry.tokens_used}")
        
        print("\n" + "=" * 80)
        
        # Question
        print("❓ QUESTION:")
        print("-" * 40)
        print(entry.question)
        print()
        
        # Answer
        print("💬 ANSWER:")
        print("-" * 40)
        print(entry.answer)
        
        # Context if available
        if entry.context:
            print("\n📖 CONTEXT:")
            print("-" * 40)
            for title, content in entry.context.items():
                print(f"• {title}: {content[:200]}{'...' if len(content) > 200 else ''}")
        
    except Exception as e:
        logger.error(f"Error showing entry: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
